package com.cc.data_explore.gui.sheet;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cc.data_explore.logic.mybatis.DbHelper;
import com.cc.data_explore.logic.mybatis.mapper.sub.FileDataMapper;
import com.cc.data_explore.logic.mybatis.model.FileData;
import de.saxsys.mvvmfx.ViewModel;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import lombok.Getter;
import lombok.Setter;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.dromara.hutool.json.JSONUtil;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cc
 * @version 1.0
 * @since 2025/4/4
 */
@Getter
public class SheetDataDialogViewModel implements ViewModel {

    public static final String COLUMN_CHANGE = "columnChange";

    private final ObservableList<Map<String, String>> items = FXCollections.observableArrayList();

    private final ObservableMap<String, String> columnMap = FXCollections.observableMap(new LinkedHashMap<>());

    @Setter
    private Long sheetId;

    public void initData(Long sheetId) {
        setSheetId(sheetId);
        loadData();
    }


    public void loadData() {
        SqlSessionFactory sqlSessionFactory = DbHelper.getInstance().getSqlSessionFactory();
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            FileDataMapper mapper = sqlSession.getMapper(FileDataMapper.class);
            List<FileData> fileData = mapper.selectList(Wrappers.<FileData>lambdaQuery().eq(FileData::getSheetId, sheetId));
            FileData defaultHeadData = fileData.get(0);
            if (columnMap.isEmpty() && defaultHeadData != null) {
                String colContent = defaultHeadData.getDataContent();
                Map<String, String> colMap = JSONUtil.parse(colContent).toBean(Map.class);
                columnMap.putAll(colMap);
                publish(COLUMN_CHANGE);
            }
            for (FileData fileDatum : fileData) {
                String dataContent = fileDatum.getDataContent();
                Map<String, String> parse = JSONUtil.parse(dataContent).toBean(Map.class);
                items.add(parse);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
